﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.Crm;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy.Metadata;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Metadata;
using System.IO;
using System.Configuration;


namespace Entitiy_Clean_up
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an authentication token.
            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.OrganizationName = ConfigurationManager.AppSettings["OrganizationName"];

            // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
            token.AuthenticationType = 0;

            // Create the metadata Web service.
            MetadataService metadataService = new MetadataService();
            var url = ConfigurationManager.AppSettings["Server"]+ ":" +
                                  ConfigurationManager.AppSettings["Port"]+
                                  "/MSCRMServices/2007/MetadataService.asmx";

            metadataService.Url = url;

            metadataService.CrmAuthenticationTokenValue = token;

            var credential = new NetworkCredential(ConfigurationManager.AppSettings["UserName"],
                                                    ConfigurationManager.AppSettings["Password"],
                                                    ConfigurationManager.AppSettings["Domain"]);

            metadataService.Credentials = credential;
            metadataService.PreAuthenticate = true;

            // Create the request to get all attribute
            RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();
            // Retrieve only the currently published changes, ignoring the changes that have
            // not been published.
            entityRequest.RetrieveAsIfPublished = false;
            entityRequest.LogicalName = ConfigurationManager.AppSettings["Entitiy"];
            entityRequest.EntityItems = EntityItems.IncludeAttributes;

            // Execute the request
            RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)metadataService.Execute(entityRequest);

            // Access the retrieved entity
            EntityMetadata retrievedEntityMetadata = entityResponse.EntityMetadata;

            foreach (var attribute in retrievedEntityMetadata.Attributes)
            {

                try
                {
                    // Create the request.
                    DeleteAttributeRequest deleteAttribute = new DeleteAttributeRequest();
                    //deleteAttribute.LogicalName = "msa_eservicesaccesslevel";
                    deleteAttribute.LogicalName = attribute.LogicalName;
                    deleteAttribute.EntityLogicalName = EntityName.contact.ToString();

                    // Execute the request.
                    DeleteAttributeResponse deleteResponse = (DeleteAttributeResponse)metadataService.Execute(deleteAttribute);
                    Console.WriteLine("Attribute deleted:" + attribute.SchemaName);
                    Log("Attribute deleted:" + attribute.SchemaName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Attribute skiped:" + attribute.LogicalName + " - " + e.Message);
                    Log("Attribute skiped:" + attribute.LogicalName + " - " + e.Message);
                }
            }
        }

        public static void Log(string text)
        {
            using (StreamWriter w = File.AppendText("log.txt"))
            {
                w.WriteLine(text);
                w.Close();
            }
        }
    }
}
